package com.geek.video.service.impl;

import com.geek.video.enums.ResponseEnum;
import com.geek.video.exception.GlobalException;
import com.geek.video.mapper.UserInfoDao;
import com.geek.video.domain.UserInfo;
import com.geek.video.service.UserInfoService;
import com.geek.video.service.dto.UserInfoDTO;
import com.geek.video.utils.BeanAndMapTransform;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户表(UserInfo)表服务实现类
 *
 * @author qinxh
 * @since 2021-01-25 16:33:42
 */
@Service("userInfoService")
@Transactional(rollbackFor = Exception.class)
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoDao userInfoDao;


    @Override
    public UserInfoDTO queryById(Integer id) {

        if (id == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        UserInfo userInfo = this.userInfoDao.queryById(id);
        UserInfoDTO dto = new UserInfoDTO();
        if (userInfo == null) {
            return dto;
        }
        BeanUtils.copyProperties(userInfo, dto);
        return dto;
    }

    @Override
    public List<UserInfoDTO> queryAll(UserInfoDTO userInfo) {

        List<UserInfo> list = this.userInfoDao.queryAll(BeanAndMapTransform.bean2Map(userInfo));

        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(m -> {
            UserInfoDTO dto = new UserInfoDTO();
            BeanUtils.copyProperties(m, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public UserInfoDTO insert(UserInfoDTO userInfo) {

        if (userInfo == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        UserInfo u = new UserInfo();
        BeanUtils.copyProperties(userInfo, u);
        this.userInfoDao.insert(u);

        userInfo.setId(u.getId());
        return userInfo;
    }

    @Override
    public UserInfoDTO update(UserInfoDTO userInfo) {

        if (userInfo == null || userInfo.getId() == null) {
            throw new GlobalException(ResponseEnum.PARAM_EMPTY);
        }

        UserInfo u = new UserInfo();
        BeanUtils.copyProperties(userInfo, u);
        this.userInfoDao.update(u);

        return this.queryById(userInfo.getId());
    }

    @Override
    public Boolean deleteById(Integer id) {

        return this.userInfoDao.deleteById(id) > 0;
    }
}